package com.gmail.skwong.speedplayer;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Class for storing BPM information about songs in an SQLite database
 * 
 * @author Stephen
 * 
 */
public class TempoDatabase extends SQLiteOpenHelper {

	static final String dbName = "tempoDB";
	static final String tempoTable = "Tempos";
	static final String colSongTitle = "SongTitle";
	static final String colSongTempo = "SongTempo";

	public TempoDatabase(Context context) {
		super(context, dbName, null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE " + tempoTable + "(" + colSongTitle
				+ " VARCHAR PRIMARY KEY , " + colSongTempo + " INTEGER)");

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS " + tempoTable);
		onCreate(db);
	}

	public boolean isSongInDB(String title) {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.query(tempoTable, new String[] { colSongTitle,
				colSongTempo }, colSongTitle + "=?", new String[] { title },
				null, null, null, null);
		if (cursor != null) {
			return true;
		} else {
			return false;
		}
	}

	public void addSong(String title, int tempo) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(colSongTitle, title);
		values.put(colSongTempo, tempo);

		db.insert(tempoTable, null, values);
	}

	public String getSongForTempo(int tempo) {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.query(tempoTable, new String[] { colSongTitle,
				colSongTempo }, colSongTempo + "=?",
				new String[] { String.valueOf(tempo) }, null, null, "RANDOM()",
				"1");
		if (cursor == null) {
			return null;
		} else {
			cursor.moveToFirst();
			return cursor.getString(0);
		}
	}
}
